//
//  ViewController.m
//  JKPhotos
//
//  Created by 王冲 on 2019/6/15.
//  Copyright © 2019 王冲. All rights reserved.
//

#import "ViewController.h"
#import <SVProgressHUD.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#import "JKPhotosKit.h"
#import "TZImagePickerController.h"

@interface ViewController ()<TZImagePickerControllerDelegate>

@property(nonnull,strong) UIImageView *photoimageView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    self.view.backgroundColor = [UIColor greenColor];
    
    self.photoimageView= [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 200, 200)];
    self.photoimageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://i1.hdslb.com/bfs/archive/71c164dbf966557824f530f6756066e659931d28.jpg"]]];
    [self.view addSubview:self.photoimageView];
    
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    

}

#pragma mark 7.封装后保存图片到自定义的相册
-(void)savePhotosToAppPhotoCollection2{
    
    UIImageView *photoimageView1 = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 200, 200)];
    photoimageView1.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://i1.hdslb.com/bfs/archive/71c164dbf966557824f530f6756066e659931d28.jpg"]]];
    
    [JKPhotosKit savePhotosToAppPhotoCollection:photoimageView1.image];
    
    
}

#pragma mark 6.保存图片到自定义的相册
-(void)savePhotosToAppPhotoCollection{
    
    // 同步操作保存到 【相机胶卷】
    
    __block PHObjectPlaceholder *placeholderForCreatedAsset;
    NSError *error = nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        
        placeholderForCreatedAsset = [PHAssetChangeRequest creationRequestForAssetFromImage:self.photoimageView.image].placeholderForCreatedAsset;
        
    } error:&error];
    
    if (error) {
        [SVProgressHUD showErrorWithStatus:@"保存图片失败"];
        return;
    }
    
    // 获得自定义相册
    PHAssetCollection *createCollection = [JKPhotosKit createPHAssetCollection];
    if (createCollection == nil) {
        [SVProgressHUD showErrorWithStatus:@"创建相册失败"];
        return;
    }
    
    // 添加刚才保存的图片到 【自定义相册】
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        // 获取自定义对象的操作对象
        PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:createCollection];
        // 把图片插入到自定义相册的第一个位置
        [request insertAssets:@[placeholderForCreatedAsset] atIndexes:[NSIndexSet indexSetWithIndex:0]];
        
    } error:&error];
    
    if (error) {
        [SVProgressHUD showErrorWithStatus:@"保存图片失败"];
    }else{
        
        [SVProgressHUD showSuccessWithStatus:@"保存图片成功"];
    }
}


#pragma mark 5.查询一个相册：不存在就创建，存在做其他的操作
-(void)createAndfetchPhotoCollection{
    
    // 获取app的名字
    NSString *appName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
    
    /**
     PHAssetCollectionTypeAlbum      = 1, 自定义相册(普通的相册)
     PHAssetCollectionTypeSmartAlbum = 2, 智能相册(系统自带的相册)，如：Camera Roll
     PHAssetCollectionTypeMoment     = 3, 按照时刻分的相册
     */
    
    // 相机胶卷相册，打印：Camera Roll
    // PHFetchResult<PHAssetCollection *> *collections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil];
    // 自定义相册，打印：自定义相册的名字
    PHFetchResult<PHAssetCollection *> *collections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    
    // 自己的相册
    PHAssetCollection *appCollection = nil;
    
    for (PHAssetCollection *collection in collections) {
        
        NSLog(@"相册的名字=%@",collection.localizedTitle);
        
        if ([collection.localizedTitle isEqualToString:appName]) {
            
            appCollection = collection;
            break;
        }
    }
    
    if (appCollection == nil) {
        
        NSError *error = nil;
        
        __block NSString *createCollectionID = nil;
        
        [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
            
            // 获取app的名字
            NSString *appName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
            // 获取相册的唯一标识符
            createCollectionID = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:appName].placeholderForCreatedAssetCollection.localIdentifier;
            
        } error:&error];
        
        if (error) {
            [SVProgressHUD showErrorWithStatus:@"创建相册失败"];
        }else{
            
            appCollection = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[createCollectionID] options:nil].firstObject;
            [SVProgressHUD showSuccessWithStatus:@"创建相册成功"];
        }
    }
    
    // 相册一定存在
    NSLog(@"相册已经存在appCollection=%@",appCollection);
    
    
}

#pragma mark 4.查询一个相册
-(void)fetchPhotoCollection{
    
    /**
     PHAssetCollectionTypeAlbum      = 1, 自定义相册(普通的相册)
     PHAssetCollectionTypeSmartAlbum = 2, 智能相册(系统自带的相册)，如：Camera Roll
     PHAssetCollectionTypeMoment     = 3, 按照时刻分的相册
     */
    
    // 相机胶卷相册，打印：Camera Roll
    // PHFetchResult<PHAssetCollection *> *collections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil];
    // 自定义相册，打印：自定义相册的名字
    PHFetchResult<PHAssetCollection *> *collections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    for (PHAssetCollection *collection in collections) {
        
        NSLog(@"相册的名字=%@",collection.localizedTitle);
    }
    
    
    
}

#pragma mark 3.创建一个相册
-(void)creatPhotoCollection{
    
    //
    NSError *error = nil;
    
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        
        // 获取app的名字
        // kCFBundleNameKey = @"CFBundleName";
        // 获取app的名字
        // NSString *appName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
        NSString *appName = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleNameKey];
        // 创建一个自定义的相册
        [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle: appName];
        
    } error:&error];
    
    if (error) {
        [SVProgressHUD showErrorWithStatus:@"创建相册失败"];
    }else{
        [SVProgressHUD showSuccessWithStatus:@"创建相册成功"];
    }
    
}


#pragma mark Photos 框架保存图片到相册
-(void)savephoto2{
    
    /**
     reason: 'This method can only be called from inside of -[PHPhotoLibrary performChanges:completionHandler:] or -[PHPhotoLibrary performChangesAndWait:error:]'
     */
    
    // 异步操作保存到相册
    /*
    [[PHPhotoLibrary sharedPhotoLibrary]performChanges:^{
        
        [PHAssetChangeRequest creationRequestForAssetFromImage:self.photoimageView.image];
        
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        
        if (error) {
            [SVProgressHUD showErrorWithStatus:@"保存失败"];
        }else{
            [SVProgressHUD showErrorWithStatus:@"保存成功"];
        }
    }];
    */
     
    // 同步操作保存到相册
    
    NSError *error = nil;
    
    
    
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        
        [PHAssetChangeRequest creationRequestForAssetFromImage:self.photoimageView.image];

    } error:&error];
    
    if (error) {
        [SVProgressHUD showErrorWithStatus:@"保存失败"];
    }else{
        [SVProgressHUD showSuccessWithStatus:@"保存成功"];
    }
    
    
    
}


#pragma mark C 语言保存图片到相册
-(void)savephoto1{
    
    NSLog(@"测试");
    // 将一个图片写到相册
    // NSPhotoLibraryAddUsageDescription 牵手需要把照片保存到您的相册
    // NSPhotoLibraryUsageDescription 牵手需要访问您的相册，发送照片
    // reason: '-[NSInvocation setArgument:atIndex:]: index (2) out of bounds [-1, 1]'
    // 参数越界错误：方法的参数个数与实际传递的参数个数不一致
    
    /**
     UIImage对象
     
     @param self.photoimageView.image： UIImage对象
     @param self 监听对象
     @param image:didFinishSavingWithError:contextInfo: 保存后所走的方法
     @return 描述文字，一般为 niul
     */
    UIImageWriteToSavedPhotosAlbum(self.photoimageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    // UIImageWriteToSavedPhotosAlbum(self.photoimageView.image, [Person new], @selector(a:b:c:), nil);
}


#pragma mark 保存成功后所走的方法
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    
    // 保存完毕
    if (error) {
        
        NSLog(@"保存失败");
    }else{
        
        NSLog(@"保存成功");
    }

   
}



/**
 // 一.保存图片到相册【相机胶卷】
    1>.C语言函数
    2>.AssetsLibrary框架 iOS9 之后开始被废弃
    3>.Photos框架 iOS 8 开始就可以用了
 
 // 二.拥有一个自定义相册
    1>.AssetsLibrary框架
    2>.Photos框架
      1：PHAsset:一个 PHAsset 对象就代表相册中的一张图片或者一个视频
        1>、查：[PHAsset fetch.....]
        2>、增删改：PHAssetChangeRequest，改变图片 (包括 图片/视频 相关的所有改动操作)
      2:PHAssetCollection: 一个PHAssetCollection就代表一个相册
        1>、查：[PHAssetCollection fetch.....]
        2>、增删改：PHAssetCollectionChangeRequest，改变相册 (包括 相册 相关的所有改动操作)

 // 三.将刚才保存到【相机胶卷中的图片】引用到【自定义的相册】
    >.AssetsLibrary框架
    >.Photos框架
 
 */


@end
